// 有几位小数
export function decimalTotal(num) {
  if (String(num).indexOf(".") === -1) return 0;
  return String(num).split(".")[1].length;
}

// 加 0.1 + 0.2
export function decimalAdd(a, b) {
  let scale = Math.pow(10, Math.max(decimalTotal(a), decimalTotal(b)));
  return (decimalMultiply(a, scale) + decimalMultiply(b, scale)) / scale;
}

// 减 0.3 - 0.2
export function decimalMinus(a, b) {
  let scale = Math.pow(10, Math.max(decimalTotal(a), decimalTotal(b)));
  return (decimalMultiply(a, scale) - decimalMultiply(b, scale)) / scale;
}

// 乘 1.001 * 100
export function decimalMultiply(a, b) {
  let scale = Math.pow(10, decimalTotal(a) + decimalTotal(b));
  return Number(String(a).replace(".", "")) * Number(String(b).replace(".", "")) / scale;
}

// 除 1.001 / 100
export function decimalDivision(a, b) {
  let scale = Math.pow(10, decimalTotal(a) + decimalTotal(b));
  return Number(String(a).replace(".", "")) / Number(String(b).replace(".", "")) / scale;
}

/**
 * 四舍五入保留小数，支持负数
 * @export
 * @param {number} num
 * @param {number} [unit=0] 保留的小数位数
 * @returns {string} 与toFixed不同，负数全部转为字符串，负数位数也补齐
 */
export function decimalToFixed(num, unit = 0) {
  if (unit <= 0 || unit > 20) {
    return `${parseInt(num, 10)}`;
  }
  let total = decimalTotal(num);
  if (total > unit) {
    // 四舍五入
    let isInto = String(num).slice(unit - total).charAt() > 4;
    let target = String(num).slice(0, unit - total);
    if (isInto) {
      return `${decimalAdd(target, 1 / Math.pow(10, unit))}`;
    } else {
      return target;
    }
  } else if (total < unit) {
    // 补0
    if (total === 0) {
      return `${num}.${"0".repeat(unit - total)}`;
    }
    return `${num}${"0".repeat(unit - total)}`;
  }
  return `${num}`;
}

// 千分位表示
export function millesimal(num) {
  let re = /\B(?=(\d{3})+$)/g;
  if (decimalTotal(num)) {
    let s = String(num).split(".");
    let int = s[0];
    let decimal = s[1];
    return `${String(int).replace(re, ',')}.${decimal}`;
  }
  return String(num).replace(re, ',');
}
